package org.jpass.dc.common.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

public class CharacterEncodingFilter implements Filter {

	protected String encoding = "utf-8";

	protected FilterConfig filterConfig = null;

	public void destroy() {

		this.encoding = null;
		this.filterConfig = null;

	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

		try {
			request.setCharacterEncoding(encoding); // 设置取得数据的字符编码
			HttpServletResponse res = (HttpServletResponse) response;
			res.setHeader("Pragma", "No-cache");
			res.setHeader("Cache-Control", "no-cache");
			res.setHeader("Pragram", "no-cache");
			
			chain.doFilter(request, response);
			
			response.setCharacterEncoding(encoding); // 设置返回文本的字符编码
		} catch (ServletException e) {
			filterConfig.getServletContext().log(e.getMessage());
		} catch (IOException e) {
			filterConfig.getServletContext().log(e.getMessage());
		}

	}

	public void init(FilterConfig filterConfig) throws ServletException {

		this.filterConfig = filterConfig;
		// 获得filter的初始化参数
		this.encoding = filterConfig.getInitParameter("encoding");

	}

}
